var ctx=window.daijia.ctx;
var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数
var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载
var searchServiceNo="";
var searchAddress="";
var searchContactsPhone="";
var gasstationDelete=window.gasstationDelete;
$(document).ready(function(){
	initdata(true);
	window.setInterval(function(){
		initdata(false);
	},1000*60);
	var deleteBtn=null;
	function deletegas() {
		$.ajax({
            type: "GET",
            url: ctx+'/gasstation/delete/'+deleteBtn.attr("data-id"),
            dataType: "json",
            success: function(data){
            	if(data.success){
            		deleteBtn.parent().parent().remove();
                    $.scojs_message('加油站删除成功', $.scojs_message.TYPE_OK);
    	                setTimeout(function(){
    						window.location.reload(true);
    					}, 800);
                } else {
                	$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
                }
            }
		});
	}
	searchServiceNo = $("#serviceNo").val();
	searchAddress = $("#address").val();
	searchContactsPhone = $("#contactsPhone").val();

	//导出
	$(document).on("click","#export_button",function(){
		window.location=ctx+"/gasstation/exportGasStation?"+"serviceNo="+searchServiceNo+
		                "&address="+searchAddress+"&contactsPhone="+searchContactsPhone;
	});


	$(document).on("click","#searchButton",function(){
		offset=0;
		searchServiceNo = $("#serviceNo").val();
		searchAddress = $("#address").val();
		searchContactsPhone = $("#contactsPhone").val();
		initdata(false);
	});
	$(document).on("click",".deletethis",function(){
		deleteBtn=$(this);
		var confirm = $.scojs_confirm({
			content: "<span style='color:red;font-size:15px;'>你真的要删除该加油站吗？删除后将不能再登录!</span>",
            action:deletegas
		});
		confirm.show();
	});
	//冻结加油站
	var freezeBtn=null;
	function freezegas() {
		$.ajax({
			type: "POST",
			url: ctx+'/gasstation/changeFreeze',
			data:{id:freezeBtn.attr("data-value"),freeze:true},
			dataType: "json",
			success: function(data){
				if(data.success){
					freezeBtn.parent().parent().remove();
						$.scojs_message('冻结成功', $.scojs_message.TYPE_OK);
					setTimeout(function(){
						window.location.reload(true);
					}, 800);
				} else {
					$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
				}
			}
		});
	}
	$(document).on("click",".changeFreeze",function(){
		freezeBtn=$(this);
		var confirm = $.scojs_confirm({
			content: "你真的要冻结该加油站吗？冻结后需解冻后才能登录该加油站!",
            action:freezegas
		});
		confirm.show();
	});
	//解冻加油站
	var changeFreezeBtn=null;

	function changeFreezegas() {
		$.ajax({
			type: "POST",
			url: ctx+'/gasstation/changeFreeze',
			data:{id:changeFreezeBtn.attr("data-value"),freeze:false},
			dataType: "json",
			success: function(data){
				if(data.success){
					changeFreezeBtn.parent().parent().remove();
						$.scojs_message('解冻成功', $.scojs_message.TYPE_OK);
					setTimeout(function(){
						window.location.reload(true);
					}, 800);
				} else {
					$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
				}
			}
		});
	}

	$(document).on("click",".freeze",function(){
		changeFreezeBtn=$(this);
		var confirm = $.scojs_confirm({
			content: "你真的要解冻该加油站吗？解冻后可以重新登录该加油站!",
			action:changeFreezegas
		});
		confirm.show();
	});

    var thisButton=null;
    //修改密码
    $(document).on("click",".updatepwd",function(){
    	thisButton = $(this);
    	$("#ok_modal").removeAttr("disabled");
    	$("#update_password_form")[0].reset();
    	$('#dialog_password').modal();
    });

    //关闭修改密码窗口
    $(".close_modal").click(function(){
    	$('#dialog_password').modal("hide");
    });

    //确定修改密码
    $("#ok_modal").click(function(){
    	var password=$.trim($("#password").val());
		if(password=='' || password.length<4){
			$.scojs_message("密码不能为空且长度至少为4个字符", $.scojs_message.TYPE_ERROR);
			return false;
		}
		var passwordconfirm=$.trim($("#passwordconfirm").val());
		if(password!=passwordconfirm){
			$.scojs_message("密码不一致", $.scojs_message.TYPE_ERROR);
			return false;
		}
		$(this).attr("disabled",true);
		$.post(ctx+'/gasstation/changepassword',{'id':thisButton.attr("data-value"),'password':password},function(data){
	        if(data.success){
	            $.scojs_message('密码修改成功', $.scojs_message.TYPE_OK);
	            $('#dialog_password').modal("hide");
	        } else {
	            $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
	        }
		},'json');
    });
	$(document).on("keydown","body",function(){
		offset=0;
		if(window.event.keyCode == 13){
			$("#searchButton").click();
		}
	});
});


  function initdata(isappend){
	$.ajax({
        url : ctx+'/gasstation/listData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"serviceNo":searchServiceNo,
        	"address":searchAddress,
        	"contactsPhone":searchContactsPhone,
        	"pager.offset":offset,
        	"limit":limit
        },
        success : function(result){
        	var newcontent = '';
        	var totalElements=result.totalElements;
        	$("#NoData").text("");

        	if(totalElements>0){
        		$(result.content).each(function(index,data){
        			var mainButton="";
        			var selectButton="";
        			mainButton="<a href='"+ctx+"/gasstation/edit/"+data.id+"' class='btn btn-primary btn-xs'>编辑</a>";
        			selectButton="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link updatepwd'>修改密码</a></li>";
        			selectButton+="<li><a href='"+ctx+"/gasstation/paymentsRecord/"+data.id+"' class='btn-link'>账户明细</a></li>";
        			selectButton+="<li><a href='"+ctx+"/gasstation/review/"+data.id+"' class='btn-link'>评价</a></li>";

        			if (data.freeze) {
        				selectButton+="<li><a href='#' class='btn-link freeze' data-value='"+data.id+"' freeze='false'>解冻</a></li>";
        			} else {
        				selectButton+="<li><a href='#' class='btn-link changeFreeze' data-value='"+data.id+"' freeze='true'>冻结</a></li>";
        			}
        			if (gasstationDelete) {
        				selectButton+="<li><a href='#' class='btn-link deletethis' data-id='"+data.id+"'>删除</a></li>";
        			}

					var freeze = data.freeze ? '冻结' : ''
        			var allButton="<div class='btn-group'>"+
							mainButton+
						  "<button type='button' class='btn "+"btn-primary"+" btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>"+
						    "<span class='caret'></span>"+
						    "<span class='sr-only'>Toggle Dropdown</span>"+
						  "</button>"+
						  "<ul class='dropdown-menu' role='menu'>"+
						  	selectButton+
						  "</ul>"+
						"</div>";
	    newcontent+="<tr class='grid-data tr-hui'  >"+
	    				"<td>"+allButton+"</td>"+
					    "<td>"+data.serviceNo+"</td>"+
					    "<td>"+data.name+"<span class='label label-warning'>"+freeze+"</span>"+"</td>"+
					    "<td>"+data.balance+"元</td>"+
					    "<td>"+data.provincial+data.city+data.county+data.address+"</td>"+
					    "<td>"+data.brand+"</td>";
	    var priceTd;
	    if (data.priceList != null && data.priceList.length !=0) {
	    	$(data.priceList).each(function(index,price){
	    		if (price.gasNum =="-10#柴油") {
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum =="-20#柴油"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum == "0#柴油"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum =="90#汽油"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum =="92#汽油"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum =="93#汽油"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum =="95#汽油"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum =="97#汽油"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum =="98#汽油"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		} else if(price.gasNum =="天然气"){
	    			if (price.price != null && price.price != 0) {
	    				priceTd+="<td>"+price.price+"/L</td>";
	    			}else {
		    			priceTd+="<td>0</td>";
		    		}
	    		}
	    	})
	    	if(data.priceList.length==9){
	    		priceTd+="<td>0</td>";
	    	}
	    } else {
	    	priceTd = "<td>0</td>"+
	    	"<td>0</td>"+
	    	"<td>0</td>"+
	    	"<td>0</td>"+
	    	"<td>0</td>"+
	    	"<td>0</td>"+
	    	"<td>0</td>"+
	    	"<td>0</td>"+
	    	"<td>0</td>";
	    	"<td>0</td>";
	    }

	    newcontent+=priceTd;
	    newcontent+="<td>"+data.contacts+"</td>"+
					    "<td>"+data.contactsPhone+"</td>";
	    if (data.telephone != null) {
	    	newcontent+="<td>"+data.telephone+"</td>";
	    } else {
	    	newcontent+="<td>"+"-"+"</td>";
	    }
	    newcontent+="</tr>";

        		});
        	}else{
        		$("#NoData").text("当前页面暂无记录 ");
        	}
        	if(!isappend){
        		$("#gasstation_tbody .grid-data").remove();
        	}
        	$("#gasstation_tbody").append(newcontent);
        	$("#gasstation_tbody .grid-data").each(function(index,element){
        		$(element).fadeIn(200+(index*35));
        	});
        	if(!hasShowPages){
        		if(!isappend){
            		currentTotalElements=result.content.length;
            		pageLoading=true;
            	}else{
            		if(currentTotalElements<totalElements){
            			currentTotalElements+=result.content.length;
            			pageLoading=true;
            		}else{
            			pageLoading=false;
            		}
            	}
        	}
        	if(hasShowPages){
    			firstLoadPages=true;
        		$(".pageshow li a").html("共"+totalElements+" 条数据");
        		$(".pagedata").paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				offset=(page-1)*limit;
        				if(!firstLoadPages){
        					initdata(false);
        				}
        				firstLoadPages=false;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
        	}else{
            		pageLoading=false;
            		hasShowPages=true;
            		$(".pageshow").show();
            		$(".pagedata").show();
            		$(".pageshow li a").html("共"+totalElements+" 条数据");
            		$(".pagedata").paging(totalElements, {
            			format: '[< ncnnn >]',
            			perpage: pagingLimit,
            			onSelect: function (page) {
            				limit=pagingLimit;
            				offset=(page-1)*limit;
            				if(!firstLoadPages){
            					initdata(false);
            				}
            				firstLoadPages=false;
            		    	return false;
            			},
            			onFormat: function (type) {
            				switch (type) {
            				case 'block': // n and c
            					if (!this.active)
            						return '';
            					else if (this.value != this.page)
            						return '<li><a href="#">' + this.value + '</a></li>';
            					return '<li class="active"><a href="#">' + this.value + '</a></li>';
            				case 'next': // >
            					return '<li><a href="#">&rsaquo;</a><li>';
            				case 'prev': // <
            						return '<li><a href="#">&lsaquo;</a><li>';
            				case 'first': // [
            						return '<li><a href="#">&laquo;</a><li>';
            				case 'last': // ]
            						return '<li><a href="#">&raquo;</a></li>';
            				}
            			}
            		});
        	}
        }
	});
}


Date.prototype.Format = function(fmt)
{
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}
